#include "widget.h"
#include "ui_widget.h"
#include <QFile>
#include <QFileDialog>
#include <qfiledialog.h>
#include<QDebug>
#include <QMessageBox>
#include <QShortcut>
#include <QWheelEvent>

Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget)
{
    ui->setupUi(this);
//    ui->textEdit->installEventFilter(this);
    QShortcut *shortcutOpen = new QShortcut(QKeySequence(tr("Ctrl+O", "File|Open")),this);
    QShortcut *shortcutSave = new QShortcut(QKeySequence(tr("Ctrl+S", "File|Save")),this);
    QShortcut *shortcutZoomIn = new QShortcut(QKeySequence(tr("Ctrl+Shift++", "File|Save")),this);
    QShortcut *shortcutZoomOut = new QShortcut(QKeySequence(tr("Ctrl+Shift+-", "File|Save")),this);

    connect(shortcutOpen, &QShortcut::activated, [=](){
        on_btnFileOpen_clicked();
    });

    connect(shortcutSave, &QShortcut::activated, [=](){
        on_btnFileSave_clicked();
    });

    connect(shortcutZoomIn, &QShortcut::activated, [=](){
        zoomIn();
    });
    connect(shortcutZoomOut, &QShortcut::activated, [=](){
        zoomOut();
    });

    //虽然上面一行代码进行widget和ui的窗口关联，但是如果发生窗口大小变化的时候，里面的布局不会随之变化
    //通过下面这行代码进行显示说明，让窗口变化时，布局及其子控件随之调整
    this->setLayout(ui->verticalLayout);
    ui->widgetButton->setLayout(ui->horizontalLayout);
    connect(ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(oncurrentIndexChanged(int)));
    connect(ui->textEdit, SIGNAL(cursorPositionChanged()), this, SLOT(oncursorPositionChanged()));
}

Widget::~Widget()
{
    delete ui;
}

void Widget::zoomIn()
{
    //获得TextEdit的当前字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;

    //改变大小，设置当前字体大小
    int newFontSize = fontSize + 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

void Widget::zoomOut()
{
    //获得TextEdit的当前字体信息
    QFont font = ui->textEdit->font();
    //获得当前字体大小
    int fontSize = font.pointSize();
    if(fontSize == -1) return;

    //改变大小，设置当前字体大小
    int newFontSize = fontSize - 1;
    font.setPointSize(newFontSize);
    ui->textEdit->setFont(font);
}

//bool Widget::eventFilter(QObject *watched, QEvent *event)
//{

////    QKeyEvent *keyEvent = (QKeyEvent*) event;

////    if(keyEvent->key() == Qt::Key_Control){
////        qDebug() << "ctrl";
////    }

//    if(event->type() == QEvent::Wheel){
//        if(QGuiApplication::keyboardModifiers() == Qt::ControlModifier){
////            qDebug() << "ctrl + wheel";
//            QWheelEvent *wheelEvent = dynamic_cast<QWheelEvent*>(event);
//            if(wheelEvent->angleDelta().y() > 0){
//                zoomIn();
//            }else if(wheelEvent->angleDelta().y() < 0){
//                zoomOut();
//            }
//            return true;
//        }
//        return false;
//    }
//}


void Widget::on_btnFileOpen_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, tr("open File"),
                                                    "E:/QT/", tr("Text(*.txt)"));
    ui->textEdit->clear();

    file.setFileName(fileName);
    if(!file.open(QIODevice::ReadWrite | QIODevice::Text)){
        qDebug() << "file open error";
    }
    this->setWindowTitle(fileName + "-课程作业");
    QTextStream in(&file);
    //    in.setCodec("UTF-8");
    //QString context = in.read(file.size());
    QString str = ui->comboBox->currentText();
    const char *c_str = str.toStdString().c_str();
    in.setCodec(c_str);
    while(!in.atEnd()){
        QString context = in.readLine();
        //        ui->textEdit->setText(context);
        ui->textEdit->append(context);
        //        qDebug() << "---------";
    }
    //    file.close();
}


void Widget::on_btnFileSave_clicked()
{
    if(!file.isOpen()){
        QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"),
                                                        "E:/QT/untitled.txt",
                                                        tr("Text (*.txt *.doc)"));
        file.setFileName(fileName);
        if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){
            qDebug() << "file open error";
        }
        this->setWindowTitle(fileName + "-课程作业");

    }
    QTextStream out(&file);
    out.setCodec(ui->comboBox->currentText().toStdString().c_str());
    QString context = ui->textEdit->toPlainText();
    out << context;
    //    file.close();


}


void Widget::on_btnFileClose_clicked()
{
    QMessageBox msgBox;
    int ret = QMessageBox::warning(this, tr("课程作业退出提示"),
                                   tr("文档已被修改。\n"
                                      "是否要保存更改？"),
                                   QMessageBox::Save | QMessageBox::Discard
                                   | QMessageBox::Cancel,
                                   QMessageBox::Save);
    switch (ret) {
    case QMessageBox::Save:
        // Save was clicked
        on_btnFileSave_clicked();
        break;
    case QMessageBox::Discard:
        // Don't Save was clicked
        ui->textEdit->clear();
        if(file.isOpen()){
            file.close();
            this->setWindowTitle("课程作业");
        }
        break;
    case QMessageBox::Cancel:
        // Cancel was clicked
        break;
    default:
        // should never be reached
        break;
    }

    //    qDebug() << file.isOpen();
}

void Widget::oncurrentIndexChanged(int index) {

    ui->textEdit->clear();
    if(file.isOpen()){
        QTextStream in(&file);
        in.setCodec(ui->comboBox->currentText().toStdString().c_str());
        file.seek(0);
        while(!in.atEnd()){
            QString context = in.readLine();
            //        ui->textEdit->setText(context);
            ui->textEdit->append(context);
            //        qDebug() << "---------";
        }
        //    file.close();
    }


}

void Widget::oncursorPositionChanged()
{
    QTextCursor cursor = ui->textEdit->textCursor();
    //qDebug() << cursor.blockNumber() + 1 << ", "<< cursor.columnNumber() + 1;
    QString blockNum = QString::number(cursor.blockNumber() + 1);
    QString columnNumber = QString::number(cursor.columnNumber() + 1);
    const QString labelMes = "列:" + blockNum + ", 行:" + columnNumber;
    ui->labelPosition->setText(labelMes);

    //    设置当前行高亮
    QList<QTextEdit::ExtraSelection> extraSelections;
    QTextEdit::ExtraSelection ext;

    //    1，知道当前行
    ext.cursor = ui->textEdit->textCursor();
    QBrush qBrush(Qt::yellow);

    //    2，颜色
    ext.format.setBackground(qBrush);
    //   配置段属性：整行显示，没有这句话不行
    ext.format.setProperty(QTextFormat::FullWidthSelection, true);

    //    3，设置
    //把ext加到ext的容器中
    extraSelections.append(ext);
    ui->textEdit->setExtraSelections(extraSelections);
}
